package com.xiaomaoguai.jsonp;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @Description :
 * @FileName: HttpRequestGetImage.java
 * @Author :WeiHui.Zhang
 * @Data : 2015年5月12日 下午4:45:45
 * @Version:V1.00
 */
public class HttpRequestGetImage {

	private final static String IMG_URL = "http://gi2.md.alicdn.com/bao/uploaded/i2/TB12s3gHpXXXXXBXFXXXXXXXXXX_!!0-item_pic.jpg_430x430q90.jpg";
	
	// 获取网络图片
	public static void getNetImage(String httpUrl, String pathName) throws IOException {
		// 返回写入图片的路径
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
		URL url = new URL(httpUrl);
		byte data[] = new byte[1024];
		HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
		InputStream inputStream = httpURLConnection.getInputStream();
		int len = 0;
		while ((len = inputStream.read(data)) != -1) {
			byteArrayOutputStream.write(data, 0, len);
		}
		FileOutputStream fileOutputStream = new FileOutputStream(pathName);
		fileOutputStream.write(byteArrayOutputStream.toByteArray());
		if (fileOutputStream != null) {
			fileOutputStream.close();
		}
		if (byteArrayOutputStream != null) {
			byteArrayOutputStream.close();
		}
	}
	
	public static void main(String[] args) throws IOException {
		getNetImage(IMG_URL, "C://ppp.jpg");
	}
}
